from pathlib import Path
import time
import sys
import inspect


def save_line_into_file_generator(filename):
    new_name = f"{time.strftime('%Y-%m-%d')}_{filename}"
    destination_file_path = Path(__file__).parent / new_name
    # w 是以覆盖写入模式
    with open(destination_file_path, "w", encoding="utf-8") as f:
        while True:
            line = yield
            if line is not None and line != "" and line != "end":
                f.write(f"【{time.strftime("%Y-%m-%d %H:%M:%S")}】 # {line}\n")
            else:
                yield "end"
                break


def read_file_generator(filename):
    file_path = Path(__file__).parent / filename

    with open(file_path, "r", encoding="utf-8") as f:

        while True:
            line = f.readline()
            if line is not None:
                yield line
            else:
                print("为空了=", line)
                raise StopIteration


read_gen = read_file_generator("test_file.txt")
write_gen = save_line_into_file_generator("java.bak.log")


while True:
    time.sleep(0.3)
    line = next(read_gen)
    if line is not None and line != "":
        print(line)

        # 如果写生成器还没有启动的话，则先启动
        if inspect.getgeneratorstate(write_gen) == "GEN_CREATED":
            next(write_gen)

        flag = write_gen.send(line)
        if flag == "end":
            print("文件写入结束")
            write_gen.close()

    else:
        print("文件读取完毕")
        write_gen.send("end")
        break
